package com.xxg.renrenproduct.dao;

import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.Indexes;
import com.xxg.renrencommon.domain.bean.ProductCollectionInfo;
import org.bson.Document;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.List;

import static org.springframework.data.mongodb.core.query.Criteria.where;

/**
 * 商品收藏dao
 *
 * @author szj
 * @date 2021/11/29
 */
@Repository
public class ProductCollectionInfoDao {
    private final MongoTemplate mongoTemplate;

    public ProductCollectionInfoDao(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
        createCollection();
    }

    /**
     * 创建collection
     */
    private void createCollection() {
        String collectionName = "productCollectionInfo";
        MongoCollection<Document> collection;
        if (!mongoTemplate.getCollectionNames().contains(collectionName)) {
            collection = mongoTemplate.createCollection(ProductCollectionInfo.class);
            createIndex(collection);
        }
    }

    /**
     * 创建索引
     *
     * @param collection 数据集
     */
    private void createIndex(MongoCollection<Document> collection) {
        collection.createIndex(Indexes.ascending("userId"));
        collection.createIndex(Indexes.ascending("shopId"));
        collection.createIndex(Indexes.ascending("skuId"));
    }

    public ProductCollectionInfo selectByUserIdAndSpuIdAndSkuId(Integer userId, Integer spuId, Integer skuId) {
        return null;
    }

    public void insert(ProductCollectionInfo productCollectionInfo) {
        productCollectionInfo.setCreateTime(new Date());
        productCollectionInfo.setUpdateTime(new Date());
        mongoTemplate.insert(productCollectionInfo);
    }

    public void deleteByUserIdAndSpuIdAndSkuId(Integer userId, Integer spuId, Integer skuId) {
        Query query = new Query(where("userId").is(userId).and("spuId").is(spuId).and("skuId").is(skuId));
        mongoTemplate.remove(query, ProductCollectionInfo.class);
    }

    public List<ProductCollectionInfo> findByUserId(int userId, Integer pageNo, Integer pageSize) {
        Query query = new Query(where("userId").is(userId));
        query.skip((pageNo - 1) * pageSize);
        query.limit(pageSize);
        return mongoTemplate.find(query, ProductCollectionInfo.class);
    }

    public List<ProductCollectionInfo> findByUserIdAndSpuId(int userId, Integer spuId) {
        Query query = new Query(where("userId").is(userId).and("spuId").is(spuId));
        return mongoTemplate.find(query, ProductCollectionInfo.class);
    }
}
